//
//  ReservationCarViewController.m
//  Park
//
//  Created by 123456 on 2017/11/8.
//  Copyright © 2017年 YTYangK. All rights reserved.
//

#import "ReservationCarViewController.h"
#import "SelectCarViewModel.h"
#import "SelectCarModel.h"
#import "UIImageView+WebCache.h"
#import "UIImage+GIF.h"
#import "Timer1CollectionViewCell.h"
#import "CarModel.h"
#import "CarViewModel.h"
#import "PlaceView.h"
#import "ConfirmOrder.h"
#import "QueryTimeviewModel.h"
#import "CarLocationViewController.h"
#import "CCActivityHUD.h"

#define Width [UIScreen mainScreen].bounds.size.width
#define SCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)


@interface ReservationCarViewController ()<NewPagedFlowViewDelegate, NewPagedFlowViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>
{
    NewPagedFlowView *pageFlowView;
    NSString *string;//总价格
    NSString *string1;//总价格
    NSString *string2;//图片
    NSString *string3;//日期
    NSString *string4;//判断日期
    NSInteger money;//余额

    UIView *view;//遮罩层
    

    PlaceView *Pview;//地点选择器
    ConfirmOrder *CView;//订单确认
    BOOL isone;//标识第一次进页面
    BOOL isone1;//标识第一次进页面
    int i;//标识今天明天后天
    int Layout;//适配布局调整位置
    int Layout1;//适配布局调整位置
    int Layout2;//适配布局调整位置


}

@property (strong, nonatomic) CCActivityHUD *activityHUD;

/**
 *  图片数组
 */
@property (nonatomic, strong) NSMutableArray *imageArray;

/**
 *  图片数据源
 */
@property (nonatomic, strong) NSMutableArray *dataArr;
/**
 *  时间数据源
 */
@property (nonatomic, strong) NSMutableArray *mutablearr;
/**
 *  选中时间数据源
 */
@property (nonatomic, strong) NSMutableArray *timerArr;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *IntermediateFloor;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *CollectionLayout;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *PlaceButtonLayout;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *BottomFloor;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *BookLayout;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *TotalIntegralLayout;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *BottomFloor1;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *BottomFloor2;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *BottomFloor3;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *BottomFloor4;

@property (nonatomic,strong)NSMutableArray *rightLabelArray;




@end



@implementation ReservationCarViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

//    [self request:i carid:self.carid];

}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    

    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self Layout];
    self.activityHUD = [CCActivityHUD new];

    self.title = @"预约专车";
    i=1;
    isone=YES;
    isone1=YES;
    //监听上车点
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeplace:) name:@"place" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeplace1:) name:@"Reception" object:nil];

    
    
    [self RequestData];

    
    [self setupUI];


    
}


-(void)RequestData
{
    

    [SelectCarViewModel requestWithUrlForSelectCar:self andParam:@{@"token":[NSUD objectForKey:@"token"]} success:^(NSMutableArray *model) {

        
        NSMutableArray *scheduingAry = [SelectCarModel mj_objectArrayWithKeyValuesArray:model];
        
        
            [self.dataArr removeAllObjects];
        
            for (NSDictionary *dic  in scheduingAry) {
                [self.dataArr addObject: dic];
                
            }
        
        
        //第一次请求
        if (isone==YES) {
            if (self.dataArr.count !=0) {
                for (int i = 0; i<1; i++) {
                    SelectCarModel *model = self.dataArr[i];
                    self.CarTitleLabel.text =model.carName;
                    self.PriceLabel.text = [NSString stringWithFormat:@"积分%@/小时",model.price];
                    self.carid = model.id;
                    self.price = model.price;
                    string1 = model.price;
                    self.carname = model.carName;
                    string2 = model.carImg;
                }
                [self request:1 carid: self.carid];
                isone = NO;
            }
     
         
        }
        
        [pageFlowView reloadData];
        
    } failure:^(NSString *error) {
        
        [MBProgressHUD showError:error toView:self.view];

    }];
    
}


- (void)setupUI {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        pageFlowView = [[NewPagedFlowView alloc] initWithFrame:CGRectMake(0, Layout1, Width, 95)];

    }else{
    
     pageFlowView = [[NewPagedFlowView alloc] initWithFrame:CGRectMake(0, Layout1, Width, Width * 12 / 18)];
    }
    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.minimumPageAlpha = 0.1;
    pageFlowView.isCarousel = NO;
    pageFlowView.orientation = NewPagedFlowViewOrientationHorizontal;
    pageFlowView.isOpenAutoScroll = YES;
    
    
    //初始化pageControl
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, pageFlowView.frame.size.height - 25, Width, 8)];
    pageFlowView.pageControl = pageControl;
    [pageFlowView addSubview:pageControl];
    
    [self.view addSubview:pageFlowView];
    
    
    //注册cell
    [self.Timecollectionview registerNib:[UINib nibWithNibName:@"Timer1CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    self.Timecollectionview.allowsMultipleSelection=YES;

    
    //BUtton上日期
    NSDate * date = [NSDate date];//当前时间
    NSDate *lastDay = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];//明天
    NSDate *nextDay = [NSDate dateWithTimeInterval:48*60*60 sinceDate:date];//后天
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM-dd";
    NSString *res = [formatter stringFromDate:date];
    NSString *res1 = [formatter stringFromDate:lastDay];
    NSString *res2 = [formatter stringFromDate:nextDay];

    //用于判断时间
    formatter.dateFormat = @"yyyy-MM-dd";
    string4 = [formatter stringFromDate:date];
    
    
    self.TodayButton.titleLabel.lineBreakMode = 0;
    self.TomorrowBUtton.titleLabel.lineBreakMode = 0;
    self.AfterTomorrowBUtton.titleLabel.lineBreakMode = 0;
    
    [self.TodayButton setTitle:[NSString stringWithFormat:@"今天%@\n%@",res,[self weekdayStringFromDate:date]] forState:UIControlStateNormal];
    [self.TodayButton setTitleColor:RGB(225, 192, 1, 1.0) forState:UIControlStateNormal];

    self.TodayButton.titleLabel.textAlignment = NSTextAlignmentCenter;

    [self.TomorrowBUtton setTitle:[NSString stringWithFormat:@"明天%@\n%@",res1,[self weekdayStringFromDate:lastDay]] forState:UIControlStateNormal];
    self.TomorrowBUtton.titleLabel.textAlignment = NSTextAlignmentCenter;

    [self.AfterTomorrowBUtton setTitle:[NSString stringWithFormat:@"后天%@\n%@",res2,[self weekdayStringFromDate:nextDay]] forState:UIControlStateNormal];
    self.AfterTomorrowBUtton.titleLabel.textAlignment = NSTextAlignmentCenter;
    string3 = self.TodayButton.titleLabel.text;

    self.placeButton.layer.cornerRadius = 10;
    self.placeButton.layer.masksToBounds = YES;

    view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    view.backgroundColor = [UIColor blackColor];
    view.alpha =0;
    [self.view  addSubview:view];

    //地点选择器
    Pview = [[NSBundle mainBundle]loadNibNamed:@"PlaceView" owner:self options:nil][0];
    Pview.frame = CGRectMake(0,SCREEN_HEIGHT+Layout,self.view.size.width,170);
    [self.view addSubview:Pview];
    
    //订单确认
    CView =[[NSBundle mainBundle]loadNibNamed:@"ConfirmOrder" owner:self options:nil][0];
    CView.layer.cornerRadius = 8;
    CView.layer.cornerRadius = 8.0f;
    CView.layer.masksToBounds = YES;
    CView.frame =CGRectMake(SCREEN_WIDTH/2+150,SCREEN_HEIGHT+Layout, 300,400);
    CView.alpha = 0;
    [CView.ConfirmBUtton addTarget:self action:@selector(Confirm) forControlEvents:UIControlEventTouchUpInside];
    
    [CView.CancelBUtton addTarget:self action:@selector(Cancel) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:CView];

    
}



#pragma mark NewPagedFlowView Delegate
- (CGSize)sizeForPageInFlowView:(NewPagedFlowView *)flowView {
    return CGSizeMake(Width - 100, (Width - 100) * 9 / 16);
}

- (void)didSelectCell:(UIView *)subView withSubViewIndex:(NSInteger)subIndex {
    
    
    SelectCarModel *list = self.dataArr[subIndex];


    CarLocationViewController *C = [[CarLocationViewController alloc]init];
    
    C.CarId = list.carId;
    
    [self.navigationController pushViewController:C animated:YES];
    
    
}

- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(NewPagedFlowView *)flowView {
    [self.rightLabelArray removeAllObjects];
    [self.timerArr removeAllObjects];

    
    SelectCarModel *model = self.dataArr[pageNumber];
    
    NSLog(@"ViewController 滚动到了第%ld页",pageNumber);
    self.CarTitleLabel.text =model.carName;
    self.PriceLabel.text = [NSString stringWithFormat:@"积分%@/小时",model.price];
    self.carid = model.id;
    string1 = model.price;
    string2 = model.carImg;
    [self request:i carid:self.carid];
    
}


#pragma mark NewPagedFlowView Datasource
- (NSInteger)numberOfPagesInFlowView:(NewPagedFlowView *)flowView {
    
    return self.dataArr.count;
    
}

- (PGIndexBannerSubiew *)flowView:(NewPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    PGIndexBannerSubiew *bannerView = [flowView dequeueReusableCell];
    if (!bannerView) {
        bannerView = [[PGIndexBannerSubiew alloc] init];
        bannerView.tag = index;
        bannerView.layer.cornerRadius = 4;
        bannerView.layer.masksToBounds = YES;
    }
    
    SelectCarModel *list = self.dataArr[index];
    //在这里下载网络图片
    [bannerView.mainImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IPHEAD,list.carImg]] placeholderImage:[UIImage imageNamed:@""]];
    
//bannerView.mainImageView.image = self.imageArray[index];
    
    return bannerView;
}



-(void)request:(int)timerid carid:(NSString *)cid{
    
    

    NSDictionary *dict =@{@"token":[NSUD objectForKey:@"token"],@"scheduledId":@(timerid),@"carId":@(cid.integerValue)};
    
    NSLog(@"%@",dict);
    
    [CarViewModel requestWithUrlForTimer:self andParam:dict success:^(NSMutableArray *model) {        
        
        
        if (model.count == 0) {
            self.GoOffWorkLabel.alpha =1;
        }else{
            self.GoOffWorkLabel.alpha =0;
        }
        
        [self.rightLabelArray removeAllObjects];
        string = [NSString stringWithFormat:@"0"];
        self.TotalAmountlabel.text = [NSString stringWithFormat:@"总积分：%@ ",string];
        
        NSMutableArray *scheduingAry = [CarModel mj_objectArrayWithKeyValuesArray:model];
        
        [self.mutablearr removeAllObjects];
        
        for (NSDictionary *dic  in scheduingAry) {
            [self.mutablearr addObject: dic];
        }
        
        if (self.mutablearr.count <=16) {
            self.pageControl.numberOfPages = 1;
        }else{
            self.pageControl.numberOfPages = 2;

        }

        [self.Timecollectionview reloadData];
        
    } failure:^(NSString *error) {
        [MBProgressHUD showError:error toView:self.view];

    }];
    
    
    
}




//collectionview代理方法
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    Timer1CollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //边框
    cell.layer.cornerRadius = 5;
    cell.Timerlabel.layer.cornerRadius = 5.0f;
    cell.Timerlabel.layer.borderWidth =0.8f;
    cell.Timerlabel.layer.borderColor = [UIColor whiteColor].CGColor;
    cell.Timerlabel.layer.masksToBounds = YES;

    
    CarModel* list = self.mutablearr[indexPath.row];
    cell.Timerlabel.text = list.timeSlot;

    NSString *str = [NSString stringWithFormat:@"%@%@",string4,[list.timeSlot substringFromIndex:5]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];

    NSDate *lastDate = [formatter dateFromString:str];
    //以 1970/01/01 GMT为基准，得到lastDate的时间戳
    long firstStamp = [lastDate timeIntervalSince1970];
 

    if ([self timestamp].integerValue >firstStamp) {
        
        cell.Timerlabel.layer.borderColor = [UIColor grayColor].CGColor;
        cell.Timerlabel.backgroundColor = [UIColor grayColor];
        cell.Timerlabel.text = @"已过期";
        cell.userInteractionEnabled = NO;
        
        
    }else{
    
    if ([list.state isEqualToString:@"2"]) {
        cell.Timerlabel.layer.borderWidth =1.2f;
        cell.Timerlabel.layer.borderColor = RGB(193, 33, 71, 1.0).CGColor;
        cell.Timerlabel.backgroundColor = RGB(193, 33, 71, 1.0);
        cell.Timerlabel.text = @"已预定";
        cell.userInteractionEnabled = NO;
    }else if([list.state isEqualToString:@"1"]){
        
        cell.Timerlabel.layer.borderWidth =1.2f;
        cell.Timerlabel.layer.borderColor = RGB(40, 130, 60, 1.0).CGColor;
        cell.Timerlabel.backgroundColor = RGB(40, 130, 60, 1.0);
        cell.Timerlabel.text = @"预定中";
        cell.userInteractionEnabled = NO;
        
    }else{

        cell.userInteractionEnabled = YES;

        if (cell.isSelected) {
            cell.Timerlabel.layer.borderColor = RGB(255, 192, 1, 1.0).CGColor;
            cell.Timerlabel.backgroundColor = RGB(255, 192, 1, 1.0);
            cell.Timerlabel.text = @"选中";

        }else{
            cell.Timerlabel.layer.borderColor = [UIColor whiteColor].CGColor;
            cell.Timerlabel.backgroundColor = [UIColor clearColor];

            }
        }
    
    }
    
    return cell;
    
}

//collectionview的显示
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.mutablearr.count;
}

//大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake(self.Timecollectionview.size.width/4, self.Timecollectionview.size.height/4);
}

//选中状态
-( void )collectionView:( UICollectionView *)collectionView didSelectItemAtIndexPath:( NSIndexPath *)indexPath{
    
    CarModel* list = self.mutablearr[indexPath.row];
    
    Timer1CollectionViewCell * cell = (Timer1CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    cell.Timerlabel.layer.borderColor = RGB(255, 192, 1, 1.0).CGColor;
    cell.Timerlabel.backgroundColor = RGB(255, 192, 1, 1.0);
    cell.Timerlabel.text = @"选中";
    
    
    
    [self.rightLabelArray addObject:list.id];

    [self.timerArr addObject:list.timeSlot];
    
    for (int i=0; i<=self.rightLabelArray.count; i++) {

        string = [NSString stringWithFormat:@"%d",i*string1.intValue];

    }
    self.TotalAmountlabel.text = [NSString stringWithFormat:@"总积分：%@ ",string];

}


// 取消选中操作
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __FUNCTION__);
    
    
    CarModel* list = self.mutablearr[indexPath.row];

    Timer1CollectionViewCell * cell = (Timer1CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    cell.Timerlabel.layer.borderColor = [UIColor whiteColor].CGColor;
    
    cell.Timerlabel.backgroundColor = [UIColor clearColor];
    cell.Timerlabel.text = list.timeSlot;

    
    [self.rightLabelArray removeObject:list.id];
    [self.timerArr removeObject:list.timeSlot];
    string = [NSString stringWithFormat:@"%d",string.intValue -string1.intValue];

    self.TotalAmountlabel.text = [NSString stringWithFormat:@"总积分：%@ ",string];
    
    
    
}

// 设置是否允许选中
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __FUNCTION__);
    return YES;
}

// 设置是否允许取消选中
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __FUNCTION__);
    return YES;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetX = scrollView.contentOffset.x;
    //  DLog(@"ScrollView offsetX = %f",offsetX/self.width);
    //  CGFloat alpha=0;
    self.pageControl.currentPage=(NSInteger)(offsetX/Width);
    
}


//选择日期
- (IBAction)DateBUtton:(UIButton *)sender {
    
    [self.rightLabelArray removeAllObjects];
    [self.timerArr removeAllObjects];

    
    string = [NSString stringWithFormat:@"0"];
    self.TotalAmountlabel.text = [NSString stringWithFormat:@"总积分：%@ ",string];
    string3 = sender.titleLabel.text;

    if (sender.tag== 1) {
        i=1;
        [self.TodayButton setTitleColor:RGB(225, 192, 1, 1.0) forState:UIControlStateNormal];
        [self.TomorrowBUtton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.AfterTomorrowBUtton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        NSDate * date = [NSDate date];//当前时间
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        //用于判断时间
        formatter.dateFormat = @"yyyy-MM-dd";
        string4 = [formatter stringFromDate:date];

        
        [self request:1 carid:self.carid];
        
        
    }else if(sender.tag ==2){
        i=2;
        [self.TomorrowBUtton setTitleColor:RGB(225, 192, 1, 1.0) forState:UIControlStateNormal];
        [self.TodayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.AfterTomorrowBUtton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        NSDate * date = [NSDate date];//当前时间
        NSDate *lastDay = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];//明天
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        //用于判断时间
        formatter.dateFormat = @"yyyy-MM-dd";
        string4 = [formatter stringFromDate:lastDay];
        
        [self request:2 carid:self.carid];
        
        
        
    }else{
        
        i=3;
        [self.AfterTomorrowBUtton setTitleColor:RGB(225, 192, 1, 1.0) forState:UIControlStateNormal];
        [self.TomorrowBUtton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.TodayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        NSDate * date = [NSDate date];//当前时间
        NSDate *nextDay = [NSDate dateWithTimeInterval:48*60*60 sinceDate:date];//后天
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        //用于判断时间
        formatter.dateFormat = @"yyyy-MM-dd";
        string4 = [formatter stringFromDate:nextDay];

        [self request:3 carid:self.carid];

        
        
    }
    
    
}
//选择上车点
- (IBAction)place:(UIButton *)sender {
    
    [UIView animateWithDuration:0.5 animations:^{
        Pview.frame =CGRectMake(0, self.view.size.height-170, self.view.size.width, 170);
        
    }completion:^(BOOL finished) {
        
        if (isone1 ==YES) {
            [self.placeButton setTitle:Pview.placeString forState:UIControlStateNormal];
            isone =NO;
        }

    }];

}
//通知中心修改上车点
- (void)changeplace:(NSNotification *)notification{

    [self.placeButton setTitle:notification.userInfo[@"place"] forState:UIControlStateNormal];
    

    
}

//通知中心前台进入刷新
- (void)changeplace1:(NSNotification *)notification{
    
    [self request:i carid:self.carid];
}



//提交订单
- (IBAction)Submit:(UIButton *)sender {
    
 money = [[NSUD objectForKey:@"money"] integerValue] - string.integerValue;
    
    
if ([self isBetweenFromHour:8 toHour:20] ==YES) {
    if (money >=0) {
    
    if ([self.placeButton.titleLabel.text isEqualToString:@"请选择上车点"]||[self.placeButton.titleLabel.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请选择上车地点" toView:self.view];
    }else if(self.rightLabelArray.count ==0){
        [MBProgressHUD showError:@"请选择预约时间" toView:self.view];

    }else{
        
        NSString *scheduledId = [self.rightLabelArray componentsJoinedByString:@","];
        
        [QueryTimeviewModel requestWithUrlForQueryTime:self andParam:@{@"token":[NSUD objectForKey:@"token"],@"scheduledTimeId":scheduledId,@"carId":@(self.carid.integerValue)} success:^(NSString *   model) {
            
            if ([model isEqualToString:@"可以预定"]) {
                
                //弹出确认订单视图
                //block比较方法，数组中可以是NSInteger，NSString（需要转换）
                NSComparator finderSort = ^(id string1,id string2){
                    
                    if ([string1 integerValue] > [string2 integerValue]) {
                        return (NSComparisonResult)NSOrderedDescending;
                    }else if ([string1 integerValue] < [string2 integerValue]){
                        return (NSComparisonResult)NSOrderedAscending;
                    }
                    else
                        return (NSComparisonResult)NSOrderedSame;
                };
                
                //数组排序：
                NSArray *resultArray = [self.timerArr sortedArrayUsingComparator:finderSort];
                
                
                [CView.dataArr removeAllObjects];
                [CView.dataArr addObjectsFromArray:resultArray];//添加shi'jian
                [CView.timertableview reloadData];
                [CView.Carimage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IPHEAD,string2]] placeholderImage:[UIImage imageNamed:@""]];
                CView.PlaceLabel.text =[NSString stringWithFormat:@"上车点：%@",self.placeButton.titleLabel.text];
                
                CView.PriceLabel.text = [NSString stringWithFormat: @"合计：%@积分",string];
                
                
                [UIView animateWithDuration:0.5 animations:^{
                    
                    view.alpha = 0.9;
                    CView.alpha = 1;
                    CView.frame =CGRectMake(SCREEN_WIDTH/2-150, SCREEN_HEIGHT/2-264, 300, 400);
                    
                }completion:^(BOOL finished) {
                    
                    
                }];
                
            }else{
                
                [MBProgressHUD showError:@"该时间已被预约,请选择空闲时间进行预约" toView:self.view];
                [self request:i carid:self.carid];
                [self.rightLabelArray removeAllObjects];
                [self.timerArr removeAllObjects];

            }
            

            
            } failure:^(NSString *error) {
                [MBProgressHUD showError:error toView:self.view];
     
                
            }];
  
    }
        }else{
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"账户积分不足支付该订单，请到前台进行充值！"toView:self.view];

        }
    
    }else{
        
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"抱歉，现在是下班时间，请在早上8:00-晚上20:00时间段内下单！" toView:self.view];
    }


}

//确认提交订单
-(void)Confirm{

    
    [self.activityHUD showWithGIFName:@"test.gif"];

        [UIView animateWithDuration:0.5 animations:^{
            view.alpha = 0;
            CView.alpha =0;
            
        }completion:^(BOOL finished) {
            
            CView.frame =CGRectMake(SCREEN_WIDTH/2+150,SCREEN_HEIGHT+Layout, 300,400);
            
        }];
        
        
        //block比较方法，数组中可以是NSInteger，NSString（需要转换）
        NSComparator finderSort = ^(id string1,id string2){
            
            if ([string1 integerValue] > [string2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }else if ([string1 integerValue] < [string2 integerValue]){
                return (NSComparisonResult)NSOrderedAscending;
            }
            else
                return (NSComparisonResult)NSOrderedSame;
        };
        
        //数组排序：
        NSArray *resultArray = [self.rightLabelArray sortedArrayUsingComparator:finderSort];
    
        
        NSString *scheduledId = [resultArray componentsJoinedByString:@","];
        
        
    NSDictionary *dic = @{@"DateId":@(i),@"scheduledId":scheduledId,@"momey":string,@"place":self.placeButton.titleLabel.text,@"phone":[NSUD objectForKey:@"MDC_userCode"],@"carid":@(self.carid.integerValue),@"token":[NSUD objectForKey:@"token"],@"payment":@"ONECARD",@"orderType":@"RESERVE_CAR"};
        
        
        [CarViewModel requestWithUrlForReserve:self andParam:dic success:^(NSString *model) {
            
            if ([model isEqualToString:@"可以预定"]) {
                
                [self.activityHUD dismissWithText:@"订单提交成功，请等待客服确认！" delay:1.4 success:YES];

                
                [NSUD setObject:[NSString stringWithFormat:@"%ld",money] forKey:@"money"];//保存余额

                [self request:i carid: self.carid];
                
            }else{
                
                
                [self.activityHUD dismissWithText:@"该时间段已经被提前预订，请重新提交新订单" delay:1.4 success:NO];

                
                [self request:i carid:self.carid];
                
                [UIView animateWithDuration:0.5 animations:^{
                    
                    view.alpha = 0;
                    CView.alpha =0;
                    CView.frame =CGRectMake(SCREEN_WIDTH/2+150,SCREEN_HEIGHT+Layout, 300,400);
                    
                }completion:^(BOOL finished) {
                    
                    
                }];
                
            }
            
            
            [self.rightLabelArray removeAllObjects];
            [self.timerArr removeAllObjects];
            
            
        } failure:^(NSString *error) {
            
            [self.activityHUD dismissWithText:error delay:1.4 success:NO];
      
        }];
        
    

}

-(void)Cancel{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        view.alpha = 0;

        CView.alpha =0;
        CView.frame =CGRectMake(SCREEN_WIDTH/2+150,SCREEN_HEIGHT+Layout, 300,400);

        
    }completion:^(BOOL finished) {
        
    }];

}


-(BOOL)judgeTimeByStartAndEnd:(NSString *)startStr EndTime:(NSString *)endStr
{
    //获取当前时间
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    // 时间格式,建议大写    HH 使用 24 小时制；hh 12小时制
    [dateFormat setDateFormat:@"yyyy:mm:HH:mm:ss"];
    NSString * todayStr=[dateFormat stringFromDate:today];//将日期转换成字符串
    today=[dateFormat dateFromString:todayStr];//转换成NSDate类型。日期置为方法默认日期
    //start end 格式 "2016-05-18 9:00:00"
    NSDate *start = [dateFormat dateFromString:startStr];
    NSDate *expire = [dateFormat dateFromString:endStr];
    
    if ([today compare:start] == NSOrderedDescending && [today compare:expire] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}


//星期判断
- (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期天", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

//获取时间戳进行对比时间是否过期
-(NSString *)timestamp{
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timestamp = [NSString stringWithFormat:@"%.0f", a];//转为字符型
    
    return timestamp;

    
}

//判断当前时间是否在某时间段内
- (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour {
    
    NSDate *dateFrom = [self getCustomDateWithHour:fromHour];
    NSDate *dateTo = [self getCustomDateWithHour:toHour];
    
    NSDate *currentDate = [NSDate date];
    if ([currentDate compare:dateFrom]==NSOrderedDescending && [currentDate compare:dateTo]==NSOrderedAscending) {
        // 当前时间在9点和10点之间
        return YES;
    }
    return NO;
}

- (NSDate *)getCustomDateWithHour:(NSInteger)hour {
    //获取当前时间
    NSDate *currentDate = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *currentComps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
    
    //设置当天的某个点
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:hour];
    
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    return [resultCalendar dateFromComponents:resultComps];
}


-(void)Layout
{
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        
        self.IntermediateFloor.constant = 250;
        self.CollectionLayout.constant = 185;
        self.PlaceButtonLayout.constant =30;
        self.BookLayout.constant =44;
        self.BottomFloor.constant = 44.5;
        self.TotalIntegralLayout.constant = 44;
        Layout = 0;
        Layout1=5;
        self.pageControl.alpha = 0;

        
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"667.0")){
        
        self.IntermediateFloor.constant = 280;
        self.CollectionLayout.constant = 215;
        self.PlaceButtonLayout.constant =30;
        self.BookLayout.constant =44;
        self.BottomFloor.constant = 44.5;
        self.TotalIntegralLayout.constant = 44;
        Layout = 0;
        Layout1=-40;
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"736.0")){
        Layout1=-40;

        Layout = 0;

        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
        
        Layout1=-20;
        self.IntermediateFloor.constant = 320;
        self.CollectionLayout.constant = 250;
        self.BottomFloor4.constant = 30;
        Layout = 35;
        self.BottomFloor1.constant = 33;
        self.BottomFloor2.constant = 30;
        self.BottomFloor3.constant = 40;
        
    }
    
    
    
}


#pragma mark --懒加载
- (NSMutableArray *)imageArray {
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}


-(NSMutableArray *)dataArr{
    if (_dataArr==nil) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}


-(NSMutableArray *)mutablearr
{
    if (!_mutablearr) {
        _mutablearr = [[NSMutableArray alloc]init];
    }
    return _mutablearr;
}
-(NSMutableArray *)rightLabelArray
{
    if (!_rightLabelArray) {
        _rightLabelArray = [[NSMutableArray alloc]init];
    }
    return _rightLabelArray;
}
-(NSMutableArray *)timerArr
{
    if (!_timerArr) {
        _timerArr = [[NSMutableArray alloc]init];
    }
    return _timerArr;
}


@end
